import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'providers/mood_provider.dart';
import 'providers/settings_provider.dart';
import 'constants/app_theme.dart';
import 'constants/app_routes.dart';
import 'constants/app_strings.dart';
import 'services/data_seeder.dart';
import 'services/mood_repository.dart';

/// 应用程序入口点
void main() async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 设置系统UI样式
  await _setupSystemUI();
  
  // 初始化示例数据
  await _initializeSampleData();
  
  // 运行应用
  runApp(const CloudMoodApp());
}

/// 设置系统UI样式
/// 配置状态栏和导航栏的外观
Future<void> _setupSystemUI() async {
  // 设置系统UI覆盖样式
  SystemChrome.setSystemUIOverlayStyle(
    const SystemUiOverlayStyle(
      // 状态栏样式
      statusBarColor: Colors.transparent, // 透明状态栏
      statusBarIconBrightness: Brightness.dark, // 深色图标
      statusBarBrightness: Brightness.light, // iOS状态栏亮度
      
      // 导航栏样式
      systemNavigationBarColor: Colors.white, // 导航栏背景色
      systemNavigationBarIconBrightness: Brightness.dark, // 深色导航图标
      systemNavigationBarDividerColor: Colors.transparent, // 透明分割线
    ),
  );
  
  // 设置首选屏幕方向（仅竖屏）
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

/// 初始化示例数据
/// 在应用首次启动时生成示例情绪记录
Future<void> _initializeSampleData() async {
  try {
    final repository = MoodRepository();
    final dataSeeder = DataSeeder(repository);
    
    // 检查是否需要生成示例数据
    final needsData = await dataSeeder.shouldSeedData();
    
    if (needsData) {
      // 生成最近30天的示例数据，每天1-3条记录
      await dataSeeder.seedData(
        daysBack: 30,
        maxRecordsPerDay: 2,
      );
      
      debugPrint('示例数据初始化完成');
    }
  } catch (e) {
    debugPrint('示例数据初始化失败: $e');
  }
}

/// Cloud Mood 应用主类
class CloudMoodApp extends StatelessWidget {
  const CloudMoodApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // 设置Provider
        ChangeNotifierProvider(
          create: (context) => SettingsProvider()..initialize(),
        ),
        
        // 情绪记录Provider
        ChangeNotifierProvider(
          create: (context) => MoodProvider()..initialize(),
        ),
      ],
      child: Consumer<SettingsProvider>(
        builder: (context, settingsProvider, child) {
          return MaterialApp(
            // 应用基本信息
            title: AppStrings.zh('app_name'),
            debugShowCheckedModeBanner: false,
            
            // 主题配置
            theme: AppTheme.lightTheme,
            darkTheme: AppTheme.darkTheme,
            themeMode: _getThemeMode(settingsProvider.themeModeString),
            
            // 国际化配置
            locale: Locale(settingsProvider.languageCode),
            supportedLocales: const [
              Locale('zh', 'CN'), // 中文
              Locale('en', 'US'), // 英文
            ],
            localizationsDelegates: const [
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            
            // 路由配置
            initialRoute: AppRoutes.initialRoute,
            routes: AppRoutes.routes,
            onGenerateRoute: AppRoutes.onGenerateRoute,
            
            // 导航观察器
            navigatorObservers: [
              _AppNavigatorObserver(),
            ],
            
            // 构建器配置
            builder: (context, child) {
              return MediaQuery(
                // 禁用系统字体缩放
                data: MediaQuery.of(context).copyWith(
                  textScaler: const TextScaler.linear(1.0),
                ),
                child: child ?? const SizedBox.shrink(),
              );
            },
          );
        },
      ),
    );
  }
  
  /// 获取主题模式
  /// [themeMode] 设置中的主题模式字符串
  ThemeMode _getThemeMode(String themeMode) {
    switch (themeMode) {
      case 'light':
        return ThemeMode.light;
      case 'dark':
        return ThemeMode.dark;
      case 'system':
      default:
        return ThemeMode.system;
    }
  }
}

/// 应用导航观察器
/// 用于监听路由变化和页面跳转
class _AppNavigatorObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    _logRouteChange('PUSH', route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    _logRouteChange('POP', route, previousRoute);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute != null && oldRoute != null) {
      _logRouteChange('REPLACE', newRoute, oldRoute);
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didRemove(route, previousRoute);
    _logRouteChange('REMOVE', route, previousRoute);
  }

  /// 记录路由变化日志
  /// [action] 操作类型
  /// [route] 当前路由
  /// [previousRoute] 前一个路由
  void _logRouteChange(
    String action,
    Route<dynamic> route,
    Route<dynamic>? previousRoute,
  ) {
    final routeName = route.settings.name ?? 'Unknown';
    final previousRouteName = previousRoute?.settings.name ?? 'None';
    
    debugPrint(
      'Route $action: $routeName (from: $previousRouteName)',
    );
  }
}